﻿CREATE PROCEDURE [dbo].[GetNextDocNumber] (
	@DocTypeId int,
	@NextDocNumber int OUTPUT
)
AS
BEGIN
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
	SET NOCOUNT ON;

IF (@DocTypeId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

UPDATE PR.DocInfo SET @NextDocNumber = NextDocNumber, 
NextDocNumber = @NextDocNumber + 1
WHERE DocTypeId = @DocTypeId

IF @@rowcount = 0 
BEGIN
	INSERT INTO PR.DocInfo (DocTypeId, NextDocNumber)
	VALUES (@DocTypeId, 2)
	SET @NextDocNumber = 1
END

RETURN 0
END


